package com.qf.web.admin.controller;

import com.qf.aop.aspect.ApiOperationLogTitle;
import com.qf.aop.async.AsyncTaskFactory;
import com.qf.api.sys.dto.TokenDTO;
import com.qf.api.sys.entity.SysUserEntity;
import com.qf.api.sys.request.RefreshTokenRequest;
import com.qf.core.enums.common.LoginStatusEnum;
import com.qf.core.response.ResponseResult;
import com.qf.core.thread.ThreadPoolManager;
import com.qf.security.jwt.util.JwtUtil;
import com.qf.security.utils.SecurityUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author: sin
 * @Date: 2025/5/6 18:24
 * @Description:
 **/
@RestController
@Slf4j
@RequestMapping("/auth")
@ApiOperationLogTitle("认证模块")
@Tag(name = "01.鉴权接口")
public class AuthController {

    @Resource
    private JwtUtil jwtUtil;

    @Autowired
    private AsyncTaskFactory asyncTaskFactory;

    /**
     * 刷新token 根据旧的token生成新的token,过期时间延迟
     */
    @Operation(description = "刷新token")
    @PostMapping("/refreshToken")
    public ResponseResult<TokenDTO> refreshToken(@Validated @RequestBody RefreshTokenRequest refreshTokenRequest) {
        Authentication authentication = jwtUtil.getAuthentication(refreshTokenRequest.getRefreshToken());
        TokenDTO tokenDTO = TokenDTO.builder().accessToken(jwtUtil.token(authentication)).refreshToken(jwtUtil.refreshToken(authentication)).expires(jwtUtil.getExpireTime())
            .build();
        return ResponseResult.success(tokenDTO);
    }

    /**
     * 禁用logout 在 清除 SecurityContext 之前 手动记录日志
     */
    @PostMapping("/logout")
    public ResponseResult<String> logout() {
        SysUserEntity user = SecurityUtils.getUserInfo().getUser();
        // 清除认证信息  清除后AOP无法获取登录信息 不要在此记录操作日志  目前没找到合适的处理办法
        SecurityContextHolder.clearContext();
        // 记录退出登录日志
        ThreadPoolManager.execute(asyncTaskFactory.loginInfoTask(
            user.getUsername(), LoginStatusEnum.LOGOUT, LoginStatusEnum.LOGOUT.description()));
        return ResponseResult.success("退出成功");
    }
}

